local extension = Package("rfenghou_west2")
extension.extensionName = "aaa_fenghou"

local U = require "packages/utility/utility"
local RUtil = require "packages/aaa_fenghou/utility/rfenghou_util"

Fk:loadTranslationTable{
  ["rfenghou_west2"] = "诸西2",
}

local eden = General(extension, "rfenghou__eden", "west", 4, 4, General.Female)

local rfenghou__tianzhuding = fk.CreateTriggerSkill{
  name = "rfenghou__tianzhuding",
  events = {fk.GameStart},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local list = RUtil.rollDice(6, 4)
    local chosen = {}
    for i = 1, 5 do
      local choice = tonumber(room:askForChoice(player, table.map(list, function(n) return tostring(n) end), self.name, "#rfenghou__tianzhuding-choice:::rfenghou__tianzhuding"..i))
      table.insert(chosen, choice)
      table.removeOne(list, choice)
    end
    local maxHp = table.remove(chosen, 1)
    room:setPlayerMark(player, "@rfenghou__tianzhuding", table.concat(chosen, ","))
    room:changeMaxHp(player, maxHp - player.maxHp)
  end,
}

local rfenghou__tianzhuding_delay = fk.CreateTriggerSkill{
  name = "#rfenghou__tianzhuding_delay",
  priority = 1.1,
  mute = true,
  events = {fk.Damaged, fk.DrawNCards},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    if player == target and player:getMark("@rfenghou__tianzhuding") ~= 0 then
      if event == fk.Damaged and player:getMark("rfenghou__tianzhuding_draw-round") ~= 0 then return false end
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local split = player:getMark("@rfenghou__tianzhuding"):split(",")
    if event == fk.DrawNCards then
      data.n = tonumber(split[1])
    else
      room:setPlayerMark(player, "rfenghou__tianzhuding_draw-round", 1)
      player:drawCards(tonumber(split[2]), "rfenghou__tianzhuding")
    end
  end,
}
rfenghou__tianzhuding:addRelatedSkill(rfenghou__tianzhuding_delay)

local rfenghou__tianzhuding_maxcards = fk.CreateMaxCardsSkill{
  name = "#rfenghou__tianzhuding_maxcards",
  correct_func = function(self, player)
    local mark = player:getMark("@rfenghou__tianzhuding")
    if mark ~= 0 then
      return tonumber(mark:split(",")[4])
    end
  end,
}
rfenghou__tianzhuding:addRelatedSkill(rfenghou__tianzhuding_maxcards)

local rfenghou__tianzhuding_attackrange = fk.CreateAttackRangeSkill{
  name = "#rfenghou__tianzhuding_attackrange",
  correct_func = function (self, player, to)
    local mark = player:getMark("@rfenghou__tianzhuding")
    if mark ~= 0 then
      return tonumber(mark:split(",")[3])
    end
  end,
}
rfenghou__tianzhuding:addRelatedSkill(rfenghou__tianzhuding_attackrange)

eden:addSkill(rfenghou__tianzhuding)

Fk:loadTranslationTable{
  ["rfenghou__eden"] = "伊甸",
  ["#rfenghou__eden"] = "",
  ["designer:rfenghou__eden"] = "cyc",
  ["illustrator:rfenghou__eden"] = "",

  ["rfenghou__tianzhuding"] = "天注定",
  [":rfenghou__tianzhuding"] = "锁定技，游戏开始时，你抽取六个1-4之间的随机数，然后你选择其中五个，将其依次规定为你本局的:体力上限、摸牌阶段额定摸牌数、每轮首次受到伤害后的摸牌数、初始攻击范围、手牌上限加值。",
  ["#rfenghou__tianzhuding-choice"] = "天注定：请选择1个骰子数作为你的 %arg",
  ["@rfenghou__tianzhuding"] = "天注定",
  ["#rfenghou__tianzhuding_delay"] = "天注定",
  ["rfenghou__tianzhuding1"] = "体力上限",
  ["rfenghou__tianzhuding2"] = "额定摸牌数",
  ["rfenghou__tianzhuding3"] = "受伤摸牌数",
  ["rfenghou__tianzhuding4"] = "攻击范围初值",
  ["rfenghou__tianzhuding5"] = "手牌上限加值",
}

local eve = General(extension, "rfenghou__eve", "west", 3, 4, General.Female)

local TabooGate = fk.CreateTriggerSkill{
  name = "rfenghou__jinjizhimen",
  events = {fk.RoundStart, fk.AfterCardsMove},
  anim_type = "defensive",
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    if event == fk.RoundStart then return true end
    local ids = {}
    for _, move in ipairs(data) do
      if move.from == player.id then
        if move.moveReason ~= fk.ReasonUse and not (move.moveReason == fk.ReasonDiscard and move.proposer == player.id) then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Player.Hand and not table.contains(player.player_cards[Player.Hand], info.cardId) then
              if Fk:getCardById(info.cardId):getMark("@@rfenghou__jinjizhimen") == player.id then
                table.insert(ids, info.cardId)
              end
            end
          end
        end
      end
    end
    if #ids > 0 then
      self.cost_data = {cards = ids}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.RoundStart then
      local cardInfo = room:getTag("rfenghou__jinjizhimen_peachInfo")
      if cardInfo == nil then
        cardInfo = {}
        for _, card in ipairs(Fk.cards) do
          if card.name == "peach" then
            table.insert(cardInfo, {card.suit, card.number})
          end
        end
        room:setTag("rfenghou__jinjizhimen_peachInfo", cardInfo)
      end
      cardInfo = table.random(cardInfo)
      local card = room:printCard("peach", cardInfo[1], cardInfo[2])
      room:addTableMark(player, "rfenghou__jinjizhimen_record", card.id)
      room:setCardMark(card, "@@rfenghou__jinjizhimen", player.id)
      room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonJustMove, self.name, "", true)
    else
      room:delay(400)
      room:moveCardTo(self.cost_data.cards, Card.PlayerHand, player, fk.ReasonJustMove, self.name, "", true)
    end
  end,
}

local TabooGate_maxcards = fk.CreateMaxCardsSkill{
  name = "#rfenghou__jinjizhimen_maxcards",
  exclude_from = function(self, player, card)
    return card and card:getMark("@@rfenghou__jinjizhimen") == player.id and player:hasSkill(TabooGate)
  end,
}
TabooGate:addRelatedSkill(TabooGate_maxcards)

local TabooGate_draw = fk.CreateTriggerSkill{
  name = "#rfenghou__jinjizhimen_draw",
  anim_type = "drawcard",
  main_skill = TabooGate,
  priority = 0.99,
  frequency = Skill.Compulsory,
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(TabooGate) and table.find(player:getCardIds("h"), function (id)
      return Fk:getCardById(id):getMark("@@rfenghou__jinjizhimen") == player.id
    end) ~= nil then
      for _, move in ipairs(data) do
        if #move.moveInfo > 1 and ((move.from == player.id and move.to ~= player.id) or
          (move.to == player.id and move.toArea == Card.PlayerHand)) then
          return true
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, TabooGate.name)
  end,
}
TabooGate:addRelatedSkill(TabooGate_draw)

eve:addSkill(TabooGate)

local EternalCurse = fk.CreateTriggerSkill{
  name = "rfenghou__yonghengzhizhou",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player.phase == Player.Play and target == player
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local x = math.max(#table.filter(player:getTableMark("rfenghou__jinjizhimen_record"), function (id)
      return not table.contains(player.player_cards[Player.Hand], id)
    end), 1)
    for i = 1, x do
      local tos = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, 1,
      "#rfenghou__yonghengzhizhou-choose:::"..i..":"..x, self.name, false)
      local to = room:getPlayerById(tos[1])
      room:damage{from = player, to = to, damage = 1, skillName = self.name}
      if not to.dead then
        local cards = table.filter(table.connect(room.draw_pile, room.discard_pile), function (id)
          return Fk:getCardById(id).is_damage_card
        end)
        if #cards > 0 then
          room:moveCardTo(table.random(cards, 2), Card.PlayerHand, to, fk.ReasonJustMove, self.name, "", true)
        end
      end
      if player.dead then return end
    end
  end,
}
eve:addSkill(EternalCurse)

Fk:loadTranslationTable{
  ["rfenghou__eve"] = "夏娃",
  ["#rfenghou__eve"] = "",
  ["designer:rfenghou__eve"] = "cyc",
  ["illustrator:rfenghou__eve"] = "",

  ["rfenghou__jinjizhimen"] = "禁忌之门",
  [":rfenghou__jinjizhimen"] = "锁定技，每轮开始时，你获得一张不计入手牌上限的【桃】，当此牌不因使用且不因主动弃置而离开你的手牌区后，你收回之。"..
  "<br>若你持有以此法获得的【桃】，你一次性获得或失去至少两张牌后，摸一张牌。",
  ["@@rfenghou__jinjizhimen"] = "禁忌之门",
  ["#rfenghou__jinjizhimen_draw"] = "禁忌之门",

  ["rfenghou__yonghengzhizhou"] = "永恒之咒",
  [":rfenghou__yonghengzhizhou"] = "锁定技，出牌阶段开始时，你执行X次:对一名角色造成1点伤害，然后其随机获得两张伤害牌。（X为你曾因〖禁忌之门〗获得的【桃】不在手牌中的张数，至少为1）",
  ["#rfenghou__yonghengzhizhou-choose"] = "永恒之咒：对一名角色造成1点伤害，令其获得两张伤害牌(第%arg次，共%arg2次)",
}

local azazel = General(extension, "rfenghou__azazel", "west", 4)

local angerPour = fk.CreateTriggerSkill{
  name = "rfenghou__fenhenqingxie",
  events = {fk.EventPhaseStart},
  priority = 1.01, -- 更改阶段内容的技能理应时机更早……
  anim_type = "offensive",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and table.contains({Player.Draw, Player.Play, Player.Discard}, player.phase)
    and player:usedSkillTimes(self.name) < (1 + player:getMark("@rfenghou__emokuangnu"))
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local card = Fk:cloneCard("hanqing__enemy_at_the_gates")
    card.skillName = self.name
    if player:prohibitUse(card) then return false end
    local promot = "#hanqing__enemy_at_the_gates_skill"
    if table.contains({Player.Draw, Player.Play, Player.Discard}, player.phase) then
      promot = "#rfenghou__fenhenqingxie-invoke:::"..U.ConvertPhse(player.phase)
    end
    local maxNum = card.skill:getMaxTargetNum(player, card)
    local targets = table.filter(room:getOtherPlayers(player, false), function (p) return not player:isProhibited(p, card) end)
    if #targets == 0 or maxNum == 0 then return false end
    local tos = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, maxNum, promot, self.name, true)
    if #tos > 0 then
      room:sortPlayersByAction(tos)
      self.cost_data = {tos = tos}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local phase
    if table.contains({Player.Draw, Player.Play, Player.Discard}, player.phase) then
      phase = U.ConvertPhse(player.phase)
    else
      phase = room:askForChoice(player, {"phase_draw", "phase_play", "phase_discard"}, self.name, "#rfenghou__fenhenqingxie-effect")
    end
    local card = Fk:cloneCard("hanqing__enemy_at_the_gates")
    card.skillName = self.name
    room:useCard{from = player.id, tos = table.map(self.cost_data.tos, function(p) return {p} end), card = card,
    extra_data = {rfenghou__fenhenqingxie_phase = phase, rfenghou__fenhenqingxie_from = player.id}}
    return true
  end,
}

local angerPourDelay = fk.CreateTriggerSkill{
  name = "#rfenghou__fenhenqingxie_delay",
  mute = true,
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player.dead then return false end
    local effect_event = player.room.logic:getCurrentEvent():findParent(GameEvent.CardEffect)
    if effect_event then
      local eff = effect_event.data[1]
      if table.contains(eff.card.skillNames, angerPour.name) and eff.extra_data and eff.extra_data.rfenghou__fenhenqingxie_phase
      and eff.extra_data.rfenghou__fenhenqingxie_from == player.id then -- 谨防修改使用者
        for _, move in ipairs(data) do
          if move.toArea == Card.Processing and move.moveReason == fk.ReasonJustMove then
            for _, info in ipairs(move.moveInfo) do
              if table.contains(eff.extra_data.HQenemy_at_the_gates, info.cardId) then
                return true
              end
            end
          end
        end
      end
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local effect_event = room.logic:getCurrentEvent():findParent(GameEvent.CardEffect)
    if effect_event == nil then return end
    local eff = effect_event.data[1]
    local slash, nonslash = {}, {}
    for _, move in ipairs(data) do
      if move.toArea == Card.Processing and move.moveReason == fk.ReasonJustMove then
        for _, info in ipairs(move.moveInfo) do
          if table.contains(eff.extra_data.HQenemy_at_the_gates, info.cardId) then
            if Fk:getCardById(info.cardId).trueName == "slash" then
              table.insertIfNeed(slash, info.cardId)
            else
              table.insertIfNeed(nonslash, info.cardId)
            end
          end
        end
      end
    end
    room:delay(400)
    local phase = eff.extra_data.rfenghou__fenhenqingxie_phase
    if phase == "phase_draw" then
      local get = table.filter(nonslash, function (id) return room:getCardArea(id) == Card.Processing end)
      get = U.moveCardsHoldingAreaCheck(room, get)
      if #get > 0 then
        room:obtainCard(player, get, true, fk.ReasonJustMove, player.id, angerPour.name)
      end
    elseif phase == "phase_play" then
      local to = room:getPlayerById(eff.to)
      local x = math.min(#nonslash, #to:getCardIds("he"))
      if x > 0 then
        local throw = room:askForCardsChosen(player, to, x, x, "he", angerPour.name)
        room:throwCard(throw, angerPour.name, to, player)
      end
    elseif phase == "phase_discard" then
      local x = #slash
      room:askForDiscard(player, x, x, true, angerPour.name, false)
    end
  end,
}
angerPour:addRelatedSkill(angerPourDelay)

azazel:addSkill(angerPour)

local demonFury = fk.CreateTriggerSkill{
  name = "rfenghou__emokuangnu",
  events = {fk.RoundEnd},
  anim_type = "offensive",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      local count = 0
      return #player.room.logic:getActualDamageEvents(1, function (e)
        local damage = e.data[1]
        if damage.from == player then
          count = count + damage.damage
        end
        return count >= player.hp
      end, Player.HistoryRound) > 0
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local choice = room:askForChoice(player, {"loseMaxHp", "loseHp"}, self.name)
    if choice == "loseMaxHp" then
      room:changeMaxHp(player, -1)
    else
      room:loseHp(player, 1, self.name)
    end
    if player.dead then return end
    choice = room:askForChoice(player, {"#rfenghou__emokuangnu_use", "#rfenghou__emokuangnu_times"}, self.name)
    if choice == "#rfenghou__emokuangnu_times" then
      room:addPlayerMark(player, "@rfenghou__emokuangnu", 1)
    else
      angerPour:doCost(fk.EventPhaseStart, player, player, {})
    end
  end,
}
azazel:addSkill(demonFury)

Fk:loadTranslationTable{
  ["rfenghou__azazel"] = "阿撒泻勒",
  ["#rfenghou__azazel"] = "",
  ["designer:rfenghou__azazel"] = "cyc",
  ["illustrator:rfenghou__azazel"] = "",

  ["rfenghou__fenhenqingxie"] = "忿恨倾泻",
  [":rfenghou__fenhenqingxie"] = "每回合限一次，摸牌/出牌/弃牌阶段，你可以改为视为使用一张不可抵消的【兵临城下】并:获得亮出的非【杀】牌/弃置目标等同于其中非【杀】牌数量的牌/弃置等同于其中【杀】数量的牌。（不足全弃）",
  ["#rfenghou__fenhenqingxie-invoke"] = "忿恨倾泻：你可跳过 %arg，视为使用【兵临城下】(请选择目标)并执行对应效果",
  ["#rfenghou__fenhenqingxie_delay"] = "忿恨倾泻",

  ["rfenghou__emokuangnu"] = "恶魔狂怒",
  [":rfenghou__emokuangnu"] = "轮次结束时，若你本轮造成的伤害数不小于当前体力值，你可以失去1点体力或体力上限，立即执行一种〖忿恨倾泻〗的效果，或令〖忿恨倾泻〗的每回合发动次数+1。",
  ["@rfenghou__emokuangnu"] = "恶魔狂怒",
  ["#rfenghou__emokuangnu_use"] = "使用【兵临城下】",
  ["#rfenghou__emokuangnu_times"] = "增加〖忿恨倾泻〗次数",
  ["#rfenghou__fenhenqingxie-effect"] = "请选择【兵临城下】的额外效果",
}

return extension
